using System;
using XcoAppSpaces.Transport.Sockets.Auth.Contract.DoClientHandshake;
using XcoAppSpaces.Transport.Sockets.Auth.Contract;
#if SILVERLIGHT
using System.Net.Sockets;
#endif

namespace XcoAppSpaces.Transport.Sockets.Auth
{
	class SendResponse : ISendResponse
	{
		private string authenticationKey;
		//private int maxWaitForResponseSeconds;

		public void In_Connection(ConnectionWithChallenge connection)
		{
			//Console.WriteLine("SendResponse.In_Connection");
			var response = ByteExtensions.CreateHash(connection.Challenge, authenticationKey);
	    
#if !SILVERLIGHT
			try
			{
				var stream = connection.Connection.Stream;
				stream.Write(response, 0, response.Length);
				var result = stream.ReadByte();
				if (result == 1)
					Out_ValidConnection(connection.Connection);
				else
					Out_InvalidConnection(connection.Connection.Client);
			}
			catch
			{
				Out_InvalidConnection(connection.Connection.Client);
			}
#else
			connection.Connection.Client.Socket.Send(response, (s, e) =>
				{
					if (e.SocketError == SocketError.Success)
					{
						connection.Connection.Client.Socket.Receive(1, (sr, er) =>
						{
							if (e.SocketError == SocketError.Success && er.Buffer[0] == 1)
								Out_ValidConnection(connection.Connection);
							else
								Out_InvalidConnection(connection.Connection.Client);
						});
						
					}
					else
						Out_InvalidConnection(connection.Connection.Client);
				});		
#endif
		}

		public event ValidConnectionHandler Out_ValidConnection;

		public event TcpClientHandler Out_InvalidConnection;

		public void Inject(SecuritySettings securitySettings)
		{
			authenticationKey = securitySettings.AuthenticationKey;
			//maxWaitForResponseSeconds = securitySettings.SecondsAfterInvalidConnectionIsClosed;
		}
	}
}
